import React, { useState } from 'react'
import {
  Form,
  Input,
  Checkbox,
  Radio,
  InputNumber,
  Select,
  Switch,
  DatePicker,
  Button,
  AutoComplete,
  Space,
} from 'antd'
import './RegisterStyle.less'
//日期国际化
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import moment from 'moment'
//加载组件
import UploadComponent from '../Upload/Upload'
function useRegisterComponent() {
  const { Option } = Select
  // CheckBox
  const CheckboxGroup = Checkbox.Group
  // CheckBox End
  const [form] = Form.useForm()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [disabledflag, setdisableflag] = useState(false)
  //checkbox 默认选中的
  const [checkedList, setcheckedList] = useState(['跑步'])
  //checkbox 全部数据
  const [AllcheckData] = useState(['跑步', '游泳', '射击'])
  //是否全部选中
  const [CheckAll, setCheckAll] = useState(false)
  // 全选会用到
  const [indeterminate, setindeterminate] = useState(true)
  //checkbox结束
  //自动补全
  const [emailresult, setemailResult] = useState([])
  //上传图片
  const [uploadimg, setUploadImg] = useState('')
  //上传图片方法
  function handleUploadChangeUrl(url) {
    console.log('上柴图')
    console.log(url)
    setUploadImg(url)
  }
  //自动补全电邮方法
  function autoEmailSearch(value) {
    let res = []

    if (!value || value.indexOf('@') >= 0) {
      res = []
    } else {
      res = ['gmail.com', '163.com', 'qq.com'].map(
        (domain) => `${value}@${domain}`
      )
    }

    setemailResult(res)
  }
  //指定宽度
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
    },
  }
  const onFinish = (values) => {
    //必须这里使用moment格式化时间
    values.datepicker = moment(values.datepicker).format('YYYY/MM/DD')
    //要是使用checkbox的话这里必须重新赋值因为使用了全选他获取不到值
    values.checkboxall = checkedList
    //上传赋值
    values.upload = uploadimg
    console.log(values)
  }

  function validateUserName(rule, value) {
    if (value) {
      let reg = new RegExp(
        '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.[a-zA-Z0-9]{2,6}$',
        'g'
      )
      if (reg.test(value)) {
        setUsername({
          validateStatus: 'success',
          errorMsg: null,
        })
      } else {
        setUsername({
          validateStatus: 'error',
          errorMsg: '用户名必须是邮箱',
        })
      }
    } else {
      setUsername({
        validateStatus: 'error',
        errorMsg: '用户名必须填写',
      })
    }
  }
  function validatePassWord(rule, value) {
    if (value) {
      if (value !== '123') {
        setPassword({
          validateStatus: 'error',
          errorMsg: '密码必须是123',
        })
      } else {
        setPassword({
          validateStatus: 'success',
          errorMsg: null,
        })
      }
    } else {
      setPassword({
        validateStatus: 'error',
        errorMsg: '密码必须填写',
      })
    }
  }
  function handlelostfocus() {
    //不能判断error 只能判断success
    if (username.validateStatus === 'success') {
      setdisableflag(false)
    } else {
      setdisableflag(true)
    }
  }
  function onChange(date, dateString) {
    console.log(date, dateString)
    console.log('-------------------------')
    console.log(dateString)
  }
  //checkbox
  function onChangeCheckBox(checkedList) {
    setCheckAll(() => {
      return checkedList.length === AllcheckData.length
    })
    setcheckedList(checkedList)
    setindeterminate(() => {
      return !!checkedList.length && checkedList.length < AllcheckData.length
    })
  }
  //全选
  function onCheckAllChange(e) {
    console.log(e)
    setcheckedList(() => {
      if (e.target.checked) {
        return AllcheckData
      } else {
        return []
      }
    })

    setindeterminate(false)
    setCheckAll(() => {
      return e.target.checked
    })
  }
  return (
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      onFinish={onFinish}
      scrollToFirstError
    >
      {/* 用户名 */}
      <Form.Item
        name="username"
        label="用户名"
        rules={[
          {
            validator: async (rule, value) => {
              validateUserName(rule, value)
            },
          },
        ]}
        required
        help={username.errorMsg}
        validateStatus={username.validateStatus}
      >
        <Input onBlur={handlelostfocus} placeholder="输入的必须是邮箱" />
      </Form.Item>
      {/* 密码 */}
      <Form.Item
        name="password"
        label="密码"
        rules={[
          {
            validator: async (rule, value) => {
              validatePassWord(rule, value)
            },
          },
        ]}
        required
        help={password.errorMsg}
        validateStatus={password.validateStatus}
      >
        <Input.Password onBlur={handlelostfocus} placeholder="请输入密码" />
      </Form.Item>
      {/* 密码验证 */}
      <Form.Item
        name="confirm"
        label="密码确认"
        dependencies={['password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: '密码必填',
          },
          ({ getFieldValue }) => ({
            validator(rule, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve()
              }
              return Promise.reject('两次密码不一致')
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
      {/* 性别 */}
      <Form.Item name="radio-group" label="性别" required>
        <Radio.Group>
          <Radio value="male">男</Radio>
          <Radio value="female">女</Radio>
          <Radio value="knonw">不男不女</Radio>
        </Radio.Group>
      </Form.Item>
      {/*年龄*/}
      <Form.Item label="年龄">
        <Form.Item name="age" noStyle required>
          <InputNumber min={20} max={100} />
        </Form.Item>
        <span className="ant-form-text">岁</span>
      </Form.Item>
      {/* 职业选择 */}
      <Form.Item
        name="zhiye"
        label="职业"
        rules={[
          {
            required: true,
            message: '请选择你的职业',
            type: 'array',
          },
        ]}
      >
        <Select mode="multiple" placeholder="请选择你的职业">
          <Option value="程序员">程序员</Option>
          <Option value="工程师">工程师</Option>
          <Option value="维修员">维修员</Option>
        </Select>
      </Form.Item>
      {/* 选择国家 */}
      <Form.Item name="country" label="国家" hasFeedback>
        <Select placeholder="请选择国家">
          <Option value="china">China</Option>
          <Option value="usa">U.S.A</Option>
        </Select>
      </Form.Item>
      {/* 是否已婚 */}
      <Form.Item name="married" label="婚否" valuePropName="checked">
        <Switch />
      </Form.Item>
      {/* 选择日期 */}
      <Form.Item name="datepicker" label="注册日期" hasFeedback required>
        <DatePicker onChange={onChange} locale={locale} />
      </Form.Item>
      {/* 兴趣爱好 */}
      <Form.Item label="爱好" name="checkboxall">
        <Space>
          <CheckboxGroup
            options={AllcheckData}
            value={checkedList}
            onChange={onChangeCheckBox}
          />
          <Checkbox
            indeterminate={indeterminate}
            onChange={onCheckAllChange}
            checked={CheckAll}
          >
            全选
          </Checkbox>
        </Space>
      </Form.Item>
      {/* 自动完成 */}
      <Form.Item name="emailcheck" label="邮箱自动补全">
        <AutoComplete
          style={{
            width: 200,
          }}
          onSearch={autoEmailSearch}
          placeholder="请输入"
        >
          {emailresult.map((email) => (
            <Option key={email} value={email}>
              {email}
            </Option>
          ))}
        </AutoComplete>
      </Form.Item>
      {/* 文本框 */}
      <Form.Item name="Tips" label="备注">
        <Input.TextArea />
      </Form.Item>
      {/* 上传图片 */}
      <Form.Item name="upload" label="图片上传">
        <UploadComponent
          handleUploadChange={handleUploadChangeUrl}
        ></UploadComponent>
      </Form.Item>
      {/* 阅读协议 */}
      <Form.Item name="yuedu" label="阅读协议" valuePropName="checked">
        <Checkbox>
          I have read the <span>agreement</span>
        </Checkbox>
      </Form.Item>
      {/* 提交按钮 */}
      <Form.Item className="tijiao">
        <Button
          type="primary"
          htmlType="submit"
          className="login-form-button"
          disabled={disabledflag}
        >
          Login
        </Button>
        Or <div>register now!</div>
      </Form.Item>
    </Form>
  )
}

export default useRegisterComponent
